package com.micro.platform.oauth.config.oauth.support;

import com.micro.platform.oauth.framework.defaults.DefaultSubjectHandler;
import com.micro.platform.oauth.framework.domain.AccessToken;
import com.micro.platform.oauth.framework.domain.OauthContext;
import com.micro.platform.oauth.framework.domain.Subject;
import com.micro.platform.oauth.framework.interfaces.ITokenStore;
import com.micro.platform.starter.utils.StringUtils;

public class LocalSubjectHandler extends DefaultSubjectHandler {
    private ITokenStore tokenStore;
    public LocalSubjectHandler(ITokenStore tokenStore) {
        super(tokenStore);
        this.tokenStore = tokenStore;
    }

    @Override
    public AccessToken createdToken(Subject subject, OauthContext context) {
        String accessTokenStr = subject.getAccessToken();
        AccessToken accessToken = tokenStore.getAccessToken(accessTokenStr);
        if(accessToken != null){
            if(accessToken.unExpires()){
                tokenStore.removeSubject(subject.getSubjectKey());
                String refreshTokenStr = subject.getRefreshToken();
                if(StringUtils.isNotEmpty(accessTokenStr)){
                    tokenStore.removeToken(accessTokenStr);
                }
                if(StringUtils.isNotEmpty(refreshTokenStr)){
                    tokenStore.removeRefreshToken(refreshTokenStr);
                }
            }
        }
        return null;
    }
}
